package com.huan;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用ReentrantLock+Condition来实现
 * @author chenbin78
 * @version 1.0
 * @create_date 2021/4/19 10:35
 */
public class ReentrantLockCondition {

    private Map<Integer, Integer> map = new HashMap<>();

    private Integer count = 1;

    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void put() {
        for (int i = 0; i < 10; i++) {
            try {
                //加锁
                lock.lock();
                map.put(count, count);
                System.out.println(Thread.currentThread().getName() + " put：" + count);
                count ++ ;
                condition.signal();
                try {
                    //让出锁, 但是state应该不变, state应该由lock控制, 并不是condition来控制
                    condition.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } finally {
                //释放锁
                lock.unlock();
            }
        }
    }

    public void get() {
        for (int i = 0; i < 10; i++) {
            try {
                lock.lock();
                Integer integer = map.get(count - 1);
                System.out.println(Thread.currentThread().getName() + " get：" + integer);
                condition.signal();
                try {
                    condition.await(1000, TimeUnit.MILLISECONDS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } finally {
                lock.unlock();
            }
        }
    }
}